import os
import shutil
import traceback
from PyQt5.QtCore import QThread, pyqtSignal

class CleanupThread(QThread):
    """清理文件的线程类"""
    progress_updated = pyqtSignal(int)
    log_message = pyqtSignal(str)
    cleanup_completed = pyqtSignal(bool, str)
    
    def __init__(self):
        super().__init__()
        self.directories = []
        self.is_running = False
    
    def set_directories(self, directories):
        """设置要清理的目录列表"""
        self.directories = directories
    
    def run(self):
        """执行清理操作"""
        self.is_running = True
        try:
            total_dirs = len(self.directories)
            for i, dir_path in enumerate(self.directories):
                if not self.is_running:
                    self.log_message.emit("清理操作被取消")
                    self.cleanup_completed.emit(False, "清理操作被取消")
                    return
                
                if os.path.exists(dir_path):
                    try:
                        shutil.rmtree(dir_path)
                        self.log_message.emit(f"已清除目录: {dir_path}")
                    except Exception as e:
                        self.log_message.emit(f"清除目录失败: {dir_path}, 错误: {str(e)}")
                
                # 创建新目录
                if not os.path.exists(dir_path):
                    os.makedirs(dir_path)
                
                # 更新进度
                progress = int((i + 1) / total_dirs * 100)
                self.progress_updated.emit(progress)
            
            self.log_message.emit("清理操作完成")
            self.cleanup_completed.emit(True, "清理操作完成")
        except Exception as e:
            self.log_message.emit(f"清理操作出错: {str(e)}")
            self.log_message.emit(traceback.format_exc())
            self.cleanup_completed.emit(False, f"清理操作出错: {str(e)}")
        finally:
            self.is_running = False
    
    def stop(self):
        """停止清理操作"""
        self.is_running = False